package com.example.demo.leetcode.classics150;

import java.util.LinkedList;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _104组合总和
 * @description
 * @date 2023/08/11 23:16
 * <p>
 * ******************************************************
 */
public class _104组合总和 {

    List<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> track = new LinkedList<>();
    Integer trackSum = 0;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtrack(candidates, target, 0);
        return res;
    }

    private void backtrack(int[] candidates, int target, int start) {
        if (trackSum == target) {
            res.add(new LinkedList<>(track));
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            int candidate = candidates[i];
            if (trackSum + candidate > target) {
                continue;
            }
            track.add(candidate);
            trackSum += candidate;
            backtrack(candidates, target, i);
            track.removeLast();
            trackSum -= candidate;
        }
    }
}
